import Vue from 'vue'
import Router from 'vue-router'
import routes from './router'
import iView from 'iview'
import vuex from "@/store";
import {getToken} from "@/util/cookie";

Vue.use(Router)
const router = new Router({
    routes,
    isAddDynamicMenuRoutes: false,
    base: process.env.BASE_URL,
    mode: 'history'
})

/**
 * @return {boolean}
 */
function NotInMain(to) {
    if (to.path === '/')
        return false;
    let len = routes.filter(it => it.path === to.path).length
    return len > 0;
}

router.beforeEach((to, from, next) => {
    iView.LoadingBar.start()
    let token = getToken()
    if (!token || !/\S/.test(token)) {
        if (NotInMain(to)) {
            next()
        } else {
            next({name: 'login'})
        }
    } else if (to.name === 'login') {
        //有token，不能回到登录页
        next({
            name: "home"
        })
    } else if (!router.options.isAddDynamicMenuRoutes) {
        vuex.dispatch("getMenuList").then(() => {
            next(to.path)
        })
    } else {
        next()
    }
})

router.afterEach(() => {
    iView.LoadingBar.finish()
    window.scrollTo(0, 0)
})

export default router
